//
//  AppDelegate.m
//  JiongTu
//
//  Created by Dupengfei on 16/3/11.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#import "JTAppDelegate.h"
#import "UIWindow+Extension.h"

#import "LeftViewController.h"
#import "JTBaseNaviController.h"

#import "ControllerManger.h"
#import "JTUser.h"
#import "JTPushNotification.h"

#import "JTPushTool.h"

#import <AVOSCloud.h>
#import <SVProgressHUD.h>
#import <AlipaySDK/AlipaySDK.h>

#import "InfoTableViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#warning Set Dev or Release
    //最新后台
    [AVOSCloud setApplicationId:@"khmBDqLPhsv1mL3HIyouiLpa-gzGzoHsz" clientKey:@"CzNXhMIAB29l47Dvl07qtaoS"];
    //第一版
//    [AVOSCloud setApplicationId:@"L8UfG3XLvQo1WuRRDcFVtc1m-gzGzoHsz" clientKey:@"kx0JP0AP8oe5NJn7mJ5XcIQu"];
    
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    //注册通知
    [AVOSCloud registerForRemoteNotification];
    
    if ([AVUser currentUser]) {
        [[AVUser currentUser] fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            if (!error) {
                JTUser *currentUser = [JTUser userWithCurrentUser:object];
                
                [currentUser save];
            } else {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
        }];
    }
    
    NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (notificationPayload) {
        JTPushNotification *oneNotif = [JTPushNotification notificationWithRemoteNotification:notificationPayload];
        
        NSMutableArray *notifs = [JTPushTool currentNotifications];
        
        if (notifs.count) {
            [notifs insertObject:oneNotif atIndex:0];
            [JTPushTool editNotifications:notifs];
        } else {
            notifs = [NSMutableArray arrayWithObject:oneNotif];
            [JTPushTool editNotifications:notifs];
        }

    }
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumDismissTimeInterval:2.0];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor clearColor];
    
//    self.window.rootViewController = [ControllerManger sharedManager].rootVC;
    [self.window switchRootViewController];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

//注册完成后保存AVInstallation到云端
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    [currentInstallation setDeviceTokenFromData:deviceToken];
//    [currentInstallation setObject:[AVUser currentUser] forKey:@"owner"];
    [currentInstallation saveInBackground];
//    NSLog(@"%@", deviceToken);
}

//收到推送后根据程序状态转为Alert或本地通知展示
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    
    JTPushNotification *oneNotif = [JTPushNotification notificationWithRemoteNotification:userInfo];
    
    NSMutableArray *notifs = [JTPushTool currentNotifications];
    
    if (notifs.count) {
        [notifs insertObject:oneNotif atIndex:0];
        [JTPushTool editNotifications:notifs];
    } else {
        notifs = [NSMutableArray arrayWithObject:oneNotif];
        [JTPushTool editNotifications:notifs];
    }
    
    NSLog(@"pushUserInfo: %@", userInfo);
    
    if (application.applicationState == UIApplicationStateActive) {
        //程序在前台时使用Alert
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"新消息" message:userInfo[@"aps"][@"alert"] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            InfoTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myInfo"];
            vc.pushInfo = userInfo;
            [self presentViewController:vc];
        }];
        
        [alert addAction:cancel];
        [alert addAction:sure];
        //keywindow上的根控制器
        UIViewController *topRootViewController = application.keyWindow.rootViewController;
        //如果根控制器上有present的控制器，则以present出来的控制器作为根控制器
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }
        [topRootViewController presentViewController:alert animated:YES completion:nil];
        
        completionHandler(UIBackgroundFetchResultNewData);

    } else if (application.applicationState == UIApplicationStateInactive) {
        //在后台时转换成一个本地通知，显示到通知栏
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.userInfo = userInfo;
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        localNotification.alertBody = userInfo[@"aps"][@"alert"];
        localNotification.fireDate = [NSDate date];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        
        [AVAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
    } else {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}
//转为本地通知时调用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    InfoTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myInfo"];
    vc.pushInfo = notification.userInfo;
    
    [self presentViewController:vc];
}

- (void)presentViewController:(UIViewController *)viewControllerToPresent {
    JTBaseNaviController *navi = [JTBaseNaviController navigationControllerWithRootViewController:viewControllerToPresent];
    //keywindow上的根控制器
    UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    //如果根控制器上有present的控制器，则以present出来的控制器作为根控制器
    while (topRootViewController.presentedViewController)
    {
        topRootViewController = topRootViewController.presentedViewController;
    }
    [topRootViewController presentViewController:navi animated:YES completion:nil];
    //有时keywindow会被窗口以空根控制器取代（比如展示alertview或actionsheet时），此时需要用到uiview的window属性
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    int num = application.applicationIconBadgeNumber;
    if(num!= 0){
        AVInstallation *currentInstallation = [AVInstallation currentInstallation];
        [currentInstallation setBadge:0];
        [currentInstallation saveEventually];
        application.applicationIconBadgeNumber=0;
    }
    [application cancelAllLocalNotifications];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [SVProgressHUD dismiss];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"JTPayCallBackNotification" object:resultDic];
        }];
    }
    return YES;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
